package com.wendy.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendy.utils.Constants;
import com.wendy.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhuwending
 */
@Component
public class UserAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = StringUtils.isNotEmpty(header) && "XMLHttpRequest".equalsIgnoreCase(header);
        if (isAjax) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.errorResponse("没有访问权限")));
        } else if (!response.isCommitted()) {
            request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            RequestDispatcher dispatcher = request.getRequestDispatcher(Constants.DEFAULT_AUTHORITY_PAGE);
            dispatcher.forward(request, response);
        }
    }
}
